import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/user/Users.vue'
import Rights from '../components/power/Rights.vue'
import Roles from '../components/power/Roles.vue'
import Cate from '../components/goods/Cate.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  //前提Welcom是Home子页面，子路由  
  //先到Home再redirect到Welcome  先加载Home再加载Welcome  
  //redirect是自动重定向  在外层添加router 内层设置index是点击触发重定向
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      //点击权限列表而不是角色列表  加载Rights组件 
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles },
      { path: '/categories', component: Cate }
    ]
  },
]

const router = new VueRouter({
  routes
})

//路由守卫是输入地址和重定向的验证机制
//首次输入地址或者触发next('/login')重定向到其他地址都会触发beforeEach  
//重定向跳转login触发beforeEach 没有token又会重定向login   
//所以要判断是否在login  直接next()正常加载   
router.beforeEach((to, from, next) => {
  //to.path输入的地址栏的路径   from代表从哪个路径跳转而来   
  //next()正常加载  next('login')重定向并再次触发beforeEach   

  if (to.path == '/login') {
    return next();
  }
  else {
    const tokenStr = window.sessionStorage.getItem('token');
    if (!tokenStr) {
      return next('/login')
    }
    else {
      next()
    }
  }
})

export default router
